package com.lession.common;

import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @Description: 返回对象实体
 */
@Setter
@Getter
public class Ret<T> extends HashMap<String, Object> implements Serializable {
	private final String code;
	private final String msg;
	private final T data;
	
	public static RetBuilder ok() {
		return new RetBuilder("");
	}
	
	public static RetBuilder error(String code) {
		return new RetBuilder(code);
	}
	
	private Ret(String code, String msg, T data) {
		this.code = code;
		this.msg = msg;
		this.data = data;
		super.put("code", code);
		super.put("msg", msg);
		super.put("data", data);
	}
	
	public static class RetBuilder<T> {
		private String code;
		private String msg;
		private T data;
		
		RetBuilder(String code) {
			if (StringUtils.isEmpty(code)) {
				this.code = RetEnum.OPERATE_SUCCESS_INFO.getCode();
				this.msg = RetEnum.OPERATE_SUCCESS_INFO.getMsg();
			} else {
				this.code = code;
				if (StringUtils.isEmpty(msg)) {
					this.msg = RetEnum.ReturnEnumUtil.getMsg(code);
				}
			}
		}
		
		public RetBuilder<T> data(T data) {
			this.data = data;
			return this;
		}
		
		
		public RetBuilder<T> msg(String msg) {
			if (StringUtils.isNotBlank(msg)) {
				this.msg = msg;
			}
			return this;
		}
		
		public Ret<T> build() {
			return new Ret<T>(code, msg, data);
		}
	}
	
	public String toString() {
		JSONObject json = new JSONObject();
		try {
			json.put("code", code);
			json.put("msg", msg);
			json.put("data", data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toJSONString();
	}
}
